package com.xmuexp109.exp5.dao;

import com.xmuexp109.exp5.model.orderItem;
import com.xmuexp109.exp5.model.orderItemPo;
import com.xmuexp109.exp5.model.orders;
import com.xmuexp109.exp5.model.ordersPo;
import com.xmuexp109.exp5.util.ReturnObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;

@Repository

public class ordersDao {


    @Autowired
    private com.xmuexp109.exp5.mapper.ordersPoMapper ordersPoMapper;
    @Autowired
    private com.xmuexp109.exp5.mapper.orderItemPoMapper orderItemPoMapper;

    /**
     * 用ordersPo对象找orders对象
     * @param ordersPo 条件对象，所有条件为AND，仅有索引的值可以作为条件
     * @return  orders对象列表，带关联的orderItem返回
     * @param withItem 是否带关联的orderItem（有性能问题，不要一次返回太多orders对象）
     */
    public ReturnObject<List<orders>> findOrders(ordersPo ordersPo, Boolean withItem){
        List<ordersPo> ordersPos = ordersPoMapper.findOrders(ordersPo.getId());
        List<orders> retOrders = new ArrayList<>(ordersPos.size());
        orderItemPo orderItemPo =  null;
        if (withItem) {
            orderItemPo = new orderItemPo();
        }
        for (ordersPo orderpo : ordersPos){
            orders item = new orders(orderpo);
            if (withItem) {
                orderItemPo.setOrderId(orderpo.getId());
                List<orderItemPo> orderItemPos = orderItemPoMapper.findOrderItem(orderItemPo.getOrderId());
                List<orderItem> orderItemList = new ArrayList<>(orderItemPos.size());
                for (orderItemPo orderItemPo1 : orderItemPos) {
                    orderItem orderItem = new orderItem(orderItemPo1);
                    orderItemList.add(orderItem);
                }
                item.setOrderItemList(orderItemList);
            }
            retOrders.add(item);
        }
        return new ReturnObject<>(retOrders);
    }



    /**
     * 创建orders对象
     * @param orders 传入的orders对象
     * @return 返回对象ReturnObj
     */
    public ReturnObject<orders> createOrders(orders orders){
        ordersPo ordersPo = orders.gotordersPo();
        int ret = ordersPoMapper.insertOrders(ordersPo);

        if (orders.getOrderItemList() != null) {

            for (orderItem orderItem : orders.getOrderItemList()) {
                orderItemPo orderItemPo = orderItem.getOrderItemPo();

                orderItemPo.setOrderId(ordersPo.getId());
                ret = orderItemPoMapper.insertOrderItem(orderItemPo);
            }
        }
        ReturnObject<orders> returnObject = new ReturnObject<>(orders);
        return returnObject;
    }
}
